package com.byedu.utils;

/**
 * Created by Luo on 2017-06-16.
 */
public class TicketOfiice {

    private int ticketNum = 0;

    public TicketOfiice(int ticketNum) {
        super();
        this.ticketNum = ticketNum;
    }

    public int getTicketNum() {
        return ticketNum;
    }

    public void setTicketNum(int ticketNum) {
        this.ticketNum = ticketNum;
    }

    /**
     * 互斥锁:多个线程操作同一个资源时（同一对象）
     */
    public synchronized void sellOneTicket() {
        ticketNum--;
        /** 打印剩余票的数量*/
        if (ticketNum >= 0) {
            System.out.println("售票成功，剩余票数: " + ticketNum);
        } else {
            System.out.println("售票失败，票已售完！");
        }
    }

    public static void main(String[] args) {
        final TicketOfiice ticketOfiice = new TicketOfiice(100);
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                public void run() {
                    /** 当还有剩余的票的时候，就去执行*/
                    while (ticketOfiice.getTicketNum() > 0) {
                        ticketOfiice.sellOneTicket();
                        System.out.println("现");
                    }
                }
            }).start();
        }
    }

}